import {
  Injectable,
  CanActivate,
  ExecutionContext,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}
  canActivate(context: ExecutionContext): boolean {
    // 通过反射器拿到role元数据
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const body = request.body;
    return matchRoles(roles, body.role);
  }
}

const matchRoles = (roles: string[], userRoles: string): boolean => {
  if (roles.includes(userRoles)) {
    return true;
  } else {
    throw new UnauthorizedException('你没有权限', '请求失败');
    return false;
  }
};
